package com.example.cameraapplication;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.view.SurfaceView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.example.cameraapplication.utils.PermissionUtils;

import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public class CameraActivity extends AppCompatActivity implements  EasyPermissions.PermissionCallbacks {


    SurfaceView surfaceView ;
    CameraHelper cameraHelper;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);

        requestPermission();
        initData();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void initData() {

        surfaceView = findViewById(R.id.camera2_view);
        cameraHelper = new CameraHelper(this,surfaceView);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDestroy() {
        super.onDestroy();
        cameraHelper.destory();
    }

    private void showAlert(String text){
        AlertDialog alertDialog =new AlertDialog.Builder(this).create();
        alertDialog.setTitle("提示");
        alertDialog.setTitle(text);
        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"我知道了",(dialog, which) -> {

            dialog.dismiss();
        });

        alertDialog.show();
    }


    public void requestPermission(){
        if(!EasyPermissions.hasPermissions(this, PermissionUtils.permissions)){
            EasyPermissions.requestPermissions(this,"需要申请一下权限",PermissionUtils.REQUEST_PERMISSION_CODE,PermissionUtils.permissions);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull  String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {


    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull  List<String> perms) {

        showAlert("权限获取失败，请手动打开");
    }
}
